package leetcode_day._2022._202201._0110;

import java.util.ArrayDeque;
import java.util.Deque;

/**
 * @author yzh
 * @version 1.0
 * @date 2022/1/6 9:53
 * 简化路径
 * 算法：栈
 * 从头开始遍历
 *   有效文件，放入栈中
 *   '.' 忽略
 *   '..' 将顶部元素弹出
 */
public class _06_71 {
    public static void main(String[] args) {
        System.out.println(new _06_71().simplifyPath("/home//foo/"));
    }

    public String simplifyPath(String path) {
        Deque<String> stack = new ArrayDeque<>();
        int n = path.length();
        for (int i = 0; i < n; i++) {
            if (path.charAt(i) == '/') continue;
            int j = i + 1;
            while (j < n && path.charAt(j) != '/') ++j;
            String tmp = path.substring(i, j);
            if ("..".equals(tmp)) {
                if (!stack.isEmpty()) stack.pollLast();
            }else if (!".".equals(tmp)) stack.addLast(tmp);
            i = j - 1;
        }
        StringBuilder ans = new StringBuilder();
        while (!stack.isEmpty()) ans.append("/").append(stack.pollFirst());
        return ans.length() == 0 ? "/" : ans.toString();
    }

}
